package com.gwsdk.paysdk.http.request;

import com.gwsdk.open.GWApi;
import com.gwsdk.paysdk.bean.MqttInfo;
import com.gwsdk.paysdk.common.Constant;
import com.gwsdk.paysdk.entity.UserLogin;
import com.gwsdk.paysdk.floatview.GWFloatLoginView;
import com.gwsdk.paysdk.http.RequestUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import com.gwsdk.paysdk.utils.AppStatusManager;
import com.gwsdk.paysdk.utils.GWLog;
import com.gwsdk.paysdk.utils.JsonUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.gwsdk.paysdk.utils.ConfigureApp;
import com.gwsdk.paysdk.utils.SharedPreferencesUtils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.List;

public class LoginRequest {
	public static boolean LOGIN_NETWORK_ERROR;
	private static final String TAG = "LoginRequest";

	HttpUtils http;
	Handler mHandler;
	String mUserName;
	String mPassword;

	public LoginRequest(Handler mHandler, String userName, String password) {
		http = new HttpUtils();
		if (null != mHandler) {
			this.mHandler = mHandler;
		}
		if (!TextUtils.isEmpty(userName)) {
			this.mUserName = userName;
		} else {
			this.mUserName = "";
		}
		if (!TextUtils.isEmpty(password)) {
			this.mPassword = password;
		} else {
			this.mPassword = "";
		}
	}

	public void post(final String url, RequestParams params, final Context context) {
		LOGIN_NETWORK_ERROR = false;
		if(!ConfigureApp.getInstance().Configure(context)){
			return;
		}
		if (TextUtils.isEmpty(url) || null == params) {
			GWLog.e(TAG, "fun#post url is null add params is null");
			noticeResult(Constant.LOGIN_FAIL, "参数为空"+params+"==========="+url);
			return;
		}
		GWFloatLoginView.getInstance(GWApi.getApi().getContext(),1000, mUserName,false).show();
		GWLog.w(TAG, "fun#post url = " + url);
		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				String response=RequestUtil.getResponseAndUrl(responseInfo, url);
				GWLog.e(TAG, "msg:" + response);
				UserLogin loginSuccess = new UserLogin();
				loginSuccess.setPassword(mPassword);

				int status;
				try {
					JSONObject json = new JSONObject(response);
					status=json.optInt("code");
					if(status==200){
						JSONObject data = json.getJSONObject("data");
						loginSuccess.setLoginStatus("1");
						loginSuccess.setLoginMsg(json.optString("msg"));
						loginSuccess.setAccountUserId(data.optString("user_id"));
						loginSuccess.setToken(data.optString("token"));
						loginSuccess.setExtra_param(data.optString("extra_param"));
						loginSuccess.setAgeStatus(data.optInt("age_status",0));
						loginSuccess.setBirthday(data.optString("birthday",""));
						loginSuccess.setIsOpenSmallAccount(data.optInt("is_open_small_account"));
						loginSuccess.setUserName(data.optString("account", ""));
						loginSuccess.setNickname(data.optString("nickname"));
						loginSuccess.setBind_balance(data.optInt("bind_balance"));
						loginSuccess.setBalance(data.optInt("balance"));
						loginSuccess.setAge_status(data.optInt("age_status",0));
						loginSuccess.setUserIcon(data.optString("head_img"));
						loginSuccess.setReal_name(data.optString("real_name"));
						loginSuccess.setUserId(data.optString("user_id"));
						loginSuccess.setLevel(data.optString("level"));
						loginSuccess.setOpenim_id(data.optString("openim_id"));
						loginSuccess.setGroups_id(data.optString("groups_id"));
						loginSuccess.setVoice_id(data.optInt("voice_id"));
						MqttInfo mqtt = JsonUtil.toObj(data.optJSONObject("mqtt").toString(), MqttInfo.class);
						AppStatusManager.getInstance().mqtt = mqtt;
						JSONArray listSmallAccount = data.optJSONArray("small_list");
						List<UserLogin.SmallAccountEntity> list = new ArrayList<>();
						for (int i=0; i<listSmallAccount.length(); i++){
							JSONObject smallAccount = (JSONObject) listSmallAccount.get(i);
							UserLogin.SmallAccountEntity smallAccountEntity = new UserLogin.SmallAccountEntity();
							smallAccountEntity.setSmallNickname(smallAccount.optString("nickname"));
							smallAccountEntity.setSmallUserId(smallAccount.optString("small_id"));
							list.add(smallAccountEntity);
						}
						loginSuccess.setSmallAccountList(list);

						//TODO  保存账号自动登录====start
						SharedPreferencesUtils.getInstance().setLoginAccount(context,mUserName);
						SharedPreferencesUtils.getInstance().setLoginPassword(context,mPassword);
						//TODO  保存账号自动登录====end
						SharedPreferencesUtils.getInstance().setIsLogout(context,false);     //把上次注销状态  改为未注销
						SharedPreferencesUtils.getInstance().setIsThreeLogin(context,false);
						AppStatusManager.getInstance().userLogin = loginSuccess;


						noticeResult(Constant.LOGIN_SUCCESS, loginSuccess);
					}else{
						String msg = json.optString("msg");
						GWLog.e(TAG, "msg:" + msg);
						noticeResult(Constant.LOGIN_FAIL, msg);
					}
				}  catch (Exception e) {
					GWLog.e(TAG, e.toString());
					noticeResult(Constant.LOGIN_FAIL, "解析数据异常");
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				GWLog.e(TAG, "onFailure" + msg);
				GWLog.e(TAG, "onFailure" + error.getExceptionCode()+error.getStackTrace()+error.getMessage());
				noticeResult(Constant.LOGIN_FAIL, "服务器异常");
//				reLogin(mUserName,mPassword,context);
			}
		});
	}



//	private void reLogin(String account,String password,Context context){
//		if (LOGIN_NETWORK_ERROR){ //备用域名访问也失败，则登录失败
//			GWLog.e(TAG,"备用域名也无法访问，登录失败");
//			noticeResult(Constant.LOGIN_FAIL, "网络异常");
//			return;
//		}
//
//		String oldUrl = GWConstant.getInstance().getIpAddress().substring(0, GWConstant.getInstance().getIpAddress().indexOf("/sdk/"));
//		String str = oldUrl.substring(oldUrl.indexOf("://") + 3,oldUrl.indexOf(".")); //需要被替换的字符
//		String backUrl = oldUrl.replace(str,"sdkbak"); //替换为sdkbak
//		GWLog.e(TAG,"域名无法访问，将替换为备用域名：" + backUrl);
//
//		GWConstant.getInstance().setIpAddress(backUrl);
//		GWConstant.getInstance().initUrlInfo();
//
//		GWLoginActivity loginActivity = new GWLoginActivity(context);
//		loginActivity.startUserLogin(account,password,(Activity) context,true);
//
//		LOGIN_NETWORK_ERROR = true;
//	}

	private void noticeResult(int type, Object obj) {
		Message msg = new Message();
		msg.what = type;
		msg.obj = obj;
		if (null != mHandler) {
			mHandler.sendMessage(msg);
		}
	}
}
